/**
 * Javier Abellï¿½n, 23 Mayo 2006
 */
package buscador;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JApplet;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import org.apache.lucene.store.FSDirectory;
import searchPack.SearchManager;

/**
 * Applet y main de prueba del EditorHtml
 * 
 * @author Chuidiang
 */
public class PruebaEditorHtml extends JApplet
{
    protected static PruebaEditorHtml instancia = new PruebaEditorHtml();
    private PruebaEditorHtml(){}
    
    public static PruebaEditorHtml getInstance() {  
      return instancia;  
 }  
    private static final long serialVersionUID = 4049642308209162291L;
    /** Componente en el que se ve la pï¿½gina html */
    private editorHtml visorHtml;
    /** Panel que contiene el textField para la url y el botï¿½n de ir a ella */
    private JPanel panelDeControl;
    /** Scroll para el visor de html */
    private JScrollPane scroll;
    /** Panel que lo contiene todo */
    private JPanel panelPrincipal;
    private JPanel panelEmergente;
    
    private JFrame ventanaMore = new JFrame();
    private DefaultTableModel tableMoreModel = null;
    private javax.swing.JTable tableMore = null;
    private javax.swing.JScrollPane scrollTable;
    private String CurrentFile = null;
    private SearchManager searchManager;
   

    public void creaTodo(SearchManager searchManager,Container contenedor,String archivoPath,StringTokenizer tokensT,StringTokenizer tokensA,StringTokenizer tokensE)
    {
        this.CurrentFile = archivoPath;
        this.searchManager = searchManager;
        panelDeControl = new JPanel(new FlowLayout());
        creaVisorHtml(archivoPath,tokensT,tokensA,tokensE);
        anhadeTodoAlContenedor(contenedor);
    }
    private String fileToString(String archivoPath) throws FileNotFoundException, IOException{
            FileInputStream file = new FileInputStream(archivoPath);
            byte[] b = new byte[file.available ()];
            file.read(b);
            file.close ();
            String result = new String (b);
            return result;
    }
    
    private ArrayList<String> tokenToArray(StringTokenizer token){
              
            ArrayList<String> palField = new ArrayList<String>(token.countTokens());
            int maxWords = token.countTokens();
            for(int i = 0 ; i<maxWords ; i++) 
                palField.add(token.nextToken());
            return palField;
    }
   
    private String pintarResultadosExactos(StringTokenizer textoToken,ArrayList<String> field,String textActual){
        String palText = ""; 
        String palTextPartial = ""; 
        String partial = "";
        boolean match;
        while(textoToken.hasMoreTokens()){
                match = true;
                palText = textoToken.nextToken();
                if(palText.equalsIgnoreCase(field.get(0))){ 
                    palTextPartial = palText;
                        for (int i = 1; i<field.size();i++){                                           
                         palText = textoToken.nextToken(); 
                         if(palText.equalsIgnoreCase(field.get(i))){ 
                            palTextPartial = palTextPartial+" "+palText;
                         }
                         else match = false;
                        }
                         if(match){
                            partial = textActual.replaceAll(palTextPartial, "<font style=\"background-color: yellow;\">"+palTextPartial+"</font>"); 
                            textActual = partial;
                         }                                             
                }                   
            }          
        return textActual;
    }
            
    private String pintarResultados(StringTokenizer textoToken,ArrayList<String> field,String textActual){
        String palText = ""; 
        String partial = "";        
        while(textoToken.hasMoreTokens()){
                palText = textoToken.nextToken();
                for (int i = 0; i<field.size();i++){                     
                      if(palText.equalsIgnoreCase(field.get(i))){                        
                         partial = textActual.replaceAll(palText, "<font style=\"background-color: yellow;\">"+palText+"</font>"); 
                         textActual = partial;
                         }
                }                   
            }          
        return textActual;
    }
            
    private void creaVisorHtml(String archivoPath,StringTokenizer tokensT,StringTokenizer tokensA,StringTokenizer tokensE){
        visorHtml = new editorHtml();
        String resultAux = "";
        try
        {
            String result = fileToString(archivoPath);
            resultAux = result;
            resultAux=resultAux.replaceAll(";"," ");
            resultAux=resultAux.replaceAll("\\."," ");
            resultAux=resultAux.replaceAll(","," ");
            resultAux=resultAux.replaceAll(":"," ");
            resultAux=resultAux.replaceAll("\\?"," ");
            resultAux=resultAux.replaceAll("\""," ");
            resultAux=resultAux.replaceAll("!"," ");
            StringTokenizer textoToken = new StringTokenizer(resultAux);            

            if(tokensT!=null){
                ArrayList palFieldT = tokenToArray(tokensT);
                result = pintarResultados(textoToken, palFieldT, result);
            }
            if(tokensA!=null){
                ArrayList palFieldA = tokenToArray(tokensA);
                result = pintarResultados(textoToken, palFieldA, result);
            }
            if(tokensE!=null){
                ArrayList palFieldE = tokenToArray(tokensE);                        
                result = pintarResultadosExactos(textoToken, palFieldE, result);
            }
            
            visorHtml.setText(result);            
        } catch (Exception e)
        {
            muestraMensajeError();
        }
    }

    private void muestraMensajeError()
    {
        JOptionPane.showMessageDialog(
                SwingUtilities.getWindowAncestor(this),
                        "No es posible mostrar el documento seleccionado",
                        null,
                        JOptionPane.ERROR_MESSAGE);
    }

    private void anhadeTodoAlContenedor(Container contenedor)
    {
        scroll = new JScrollPane();
        panelPrincipal = new JPanel(new BorderLayout());     
        panelDeControl.setBackground(Color.BLACK);
        panelPrincipal.add(panelDeControl, BorderLayout.NORTH);
        scroll.setViewportView(visorHtml);
        panelPrincipal.add(scroll, BorderLayout.CENTER);
        contenedor.add(panelPrincipal);
    }
    private void crearPanelEmergente(){
        scrollTable = new javax.swing.JScrollPane();
        tableMore = new javax.swing.JTable();
        setName("Formulario Documentos Similares"); // NOI18N
        scrollTable.setName("scrollTable"); // NOI18N
        tableMore.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Documentos Similares"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        });
        tableMore.setName("tableMore"); 
        scrollTable.setViewportView(tableMore);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(buscador.BuscadorApp.class).getContext().getResourceMap(moreLikeThis.class);
        tableMore.getColumnModel().getColumn(0).setResizable(false);
        tableMore.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tableMore.columnModel.title0")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollTable, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );       
        tableMore.addMouseListener(clickTable);
    }
    private ActionListener botonMoreLikeThis = new ActionListener()
    {    
        public void actionPerformed(ActionEvent e)
        {       
          if (tableMore == null){
               crearPanelEmergente();
               ventanaMore.add(tableMore);
               ventanaMore.setTitle("Lista de Documentos Similares");
          } 
          
          ventanaMore.pack();
          ventanaMore.setVisible(true);
         
        }
    
    };
    
    private MouseAdapter clickTable = new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
                      if (e.getClickCount() == 2) { 
                           JFrame ventana = new JFrame();    
                           ventana.setTitle("aca titulo");
                           PruebaEditorHtml.getInstance().creaTodo(searchManager,ventana.getContentPane(),"C:/Users/Panther/Desktop/movie1/0020.html",null,null,null);
                           ventana.pack();
                           ventana.setVisible(true);                           
                      }
                 }
    };
  private void FindMoreLikeThis(){
      
  }

   
}
